<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="顾问等级名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入顾问等级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="顾问佣金比例" prop="commissionRatio">
        <el-input
          v-model="queryParams.commissionRatio"
          placeholder="请输入顾问佣金比例"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否可用" prop="useFlag">
        <el-select
          v-if="sysYesNo.length > 0"
          v-model="queryParams.useFlag"
          placeholder="请选择"
          clearable
          filterable
          style="width: 180px">
          <el-option v-for="d in sysYesNo" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
        <el-select v-else v-model="queryParams.useFlag" placeholder="加载中..." disabled style="width: 180px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:rank:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rank:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:rank:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:rank:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="顾问等级ID" align="center" prop="levelId" />
      <el-table-column label="顾问等级名称" align="center" prop="levelName" />
      <el-table-column label="顾问佣金比例" align="center" prop="commissionRatio" />
      <el-table-column label="是否可用" align="center" prop="useFlag">
        <template #default="scope">
          {{ (sysYesNo.find(i => i.value === String(scope.row.useFlag)) || {}).label || scope.row.useFlag }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rank:edit']"
          >修改</el-button>
          <el-button
            type="text"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:rank:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改顾问等级对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="顾问等级名称" prop="levelName">
          <el-input v-model="form.levelName" placeholder="请输入顾问等级名称" />
        </el-form-item>
        <el-form-item label="顾问佣金比例" prop="commissionRatio">
          <el-input v-model="form.commissionRatio" placeholder="请输入顾问佣金比例" />
        </el-form-item>
        <el-form-item label="是否可用" prop="useFlag">
          <el-radio-group v-model="form.useFlag">
            <el-radio v-for="d in sysYesNo" :key="d.value" :value="d.value">{{ d.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rank">
import { ref, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { listRank, getRank, delRank, addRank, updateRank, exportRank } from "@/api/system/rank";
import { parseTime } from '@/utils/ruoyi'
import { download } from '@/utils/request'
import { getsysYesNo } from '@/api/system/goodType'

const queryFormRef = ref()
const formRef = ref()
const sysYesNo = ref([])
const state = reactive({
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 顾问等级表格数据
  rankList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    levelName: null,
    commissionRatio: null,
    useFlag: null,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
  }
})

const { loading, exportLoading, showSearch, total, rankList, title, open, queryParams, form, rules, single, multiple } = toRefs(state)

/** 查询顾问等级列表 */
function getList() {
  loading.value = true
  listRank(queryParams.value).then(response => {
    rankList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    levelId: null,
    levelName: null,
    commissionRatio: null,
    useFlag: null,
    createBy: null,
    createTime: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  state.ids = selection.map(item => item.levelId)
  state.single = selection.length!==1
  state.multiple = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加顾问等级"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const levelId = row.levelId || state.ids[0]
  getRank(levelId).then(response => {
    form.value = response.data
    form.value.useFlag = form.value.useFlag != null ? String(form.value.useFlag) : form.value.useFlag
    open.value = true
    title.value = "修改顾问等级"
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      const formData = { ...form.value }
      if (form.value.levelId != null) {
        updateRank(formData).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRank(formData).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const levelIds = row.levelId || state.ids
  ElMessageBox.confirm('是否确认删除顾问等级编号为"' + levelIds + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    return delRank(levelIds)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  const queryParams = { ...state.queryParams }
  ElMessageBox.confirm('是否确认导出所有顾问等级数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.exportLoading = true
    return exportRank(queryParams)
  }).then(response => {
    download(response.msg)
    state.exportLoading = false
  }).catch(() => {})
}

// 加载字典数据
function loadDicts() {
  return getsysYesNo().then(res => {
    const arr = res?.data || []
    sysYesNo.value = arr.map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
  }).catch(() => { sysYesNo.value = [] })
}

loadDicts().then(() => getList())
</script>